var token;
var key;
var pwNotes;
var is_sync = localStorage.getItem("cloud_sync");
var RE_url = "http://119.91.219.142:5000/account";
// var RE_url = "http://localhost:5000/account";

function cloud_down() {
    var pwNotes = JSON.parse(localStorage.getItem("PWnotes"));
    var token = localStorage.getItem("note_token");
    if (!token) {
        dialog.alert({
            title: "错误！",
            msg: '未设置密令',
            buttons: ['确认']
        });
        return;
    }
    var key = CryptoJS.MD5(token).toString().toUpperCase();
    token = CryptoJS.MD5(token + key).toString().toUpperCase();
    dialog.remove();
    dialog.alert({
        title: "提示",
        msg: '确认同步云端？',
        buttons: ['确认','取消']
    },function (re) {
        if (re.buttonIndex == 1) {
            $.ajax({
                url: RE_url+"/download_account/" + key,
                success:function (res) {
                    dialog.remove();
                    if (res != "不存在的密令") {
                        res = JSON.parse(decrypt(res, token));
                        let res_pwNotes = res.pwNotes;
                        let res_noteMap = res.noteMap;
                        pwNotes = res_pwNotes;
                        localStorage.setItem("PWnotes", JSON.stringify(pwNotes));
                        for (let i = 0; i < pwNotes.list.length; i++) {
                            localStorage.setItem(pwNotes.list[i].noteId, JSON.stringify(res_noteMap[pwNotes.list[i].noteId]));
                        }
                        if ($("#notes").length>0)init();
                        dialog.alert({
                            title: "",
                            msg: "同步成功",
                            buttons: ['确认']
                        });
                    } else {
                        dialog.alert({
                            title: "同步失败！",
                            msg: res,
                            buttons: ['确认']
                        });
                    }
                },
                error:function () {
                    dialog.remove();
                    dialog.alert({
                        title: "同步失败！",
                        msg: '请检查网络',
                        buttons: ['确认']
                    });
                }
            })
        }
    });

}
function cloud_upload() {
    var pwNotes = JSON.parse(localStorage.getItem("PWnotes"));
    var token = localStorage.getItem("note_token");
    if (!token) {
        dialog.alert({
            title: "错误！",
            msg: '未设置密令',
            buttons: ['确认']
        });
        return;
    } else if (!pwNotes) {
        dialog.alert({
            title: "错误！",
            msg: '无数据可上传',
            buttons: ['确认']
        });
        return;
    }
    var key = CryptoJS.MD5(token).toString().toUpperCase();
    token = CryptoJS.MD5(token + key).toString().toUpperCase();
    let data = {
        pwNotes: pwNotes,
        noteMap: {}
    }
    for (let i = 0; i < pwNotes.list.length; i++) {
        data.noteMap[pwNotes.list[i].noteId] = JSON.parse(localStorage.getItem(pwNotes.list[i].noteId));
    }
    var upload_data = {
        data: encrypt(JSON.stringify(data), token).toString()
    }
    dialog.remove();
    dialog.alert({
        title: "提示",
        msg: '确认上传数据？',
        buttons: ['确认','取消']
    },function (re) {
        if (re.buttonIndex == 1) {
            $.ajax({
                url: RE_url+"/upload_account/" + key,
                type: "post",
                data: upload_data,
                success: function (res) {
                    dialog.remove();
                    dialog.alert({
                        title: "",
                        msg: res,
                        buttons: ['确认']
                    });
                },
                error: function () {
                    dialog.remove();
                    dialog.alert({
                        title: "上传失败！",
                        msg: '请检查网络',
                        buttons: ['确认']
                    });
                }
            });
        }
    });
}

//同步任务
function cloud_sync() {
    pwNotes = JSON.parse(localStorage.getItem("PWnotes"));
    token = localStorage.getItem("note_token");
    if (!token) {
        $("#tips").remove();
        $("header").after("\n" +
            "<div class=\"aui-tips aui-margin-b-15\" id=\"tips\" hidden>\n" +
            "<i class=\"aui-iconfont aui-icon-info\"></i>\n" +
            "<div class=\"aui-tips-title\">未设置密令！</div>\n" +
            "<i class=\"aui-iconfont aui-icon-close\" tapmode=\"\" onclick=\"closeTips()\"></i>\n" +
            "</div>");
        return;
    }
    key = CryptoJS.MD5(token).toString().toUpperCase();
    token = CryptoJS.MD5(token + key).toString().toUpperCase();
    $.ajax({
        url: RE_url+"/download_account/" + key,
        success:function (res) {
            // debugger;
            // console.log(res);
            if (res != "不存在的密令") {
                res = JSON.parse(decrypt(res, token));
                let res_pwNotes = res.pwNotes;
                let res_noteMap = res.noteMap;
                if (!pwNotes || !pwNotes.version || res_pwNotes.version > pwNotes.version) {
                    pwNotes = res_pwNotes;
                    if ($("#notes").length>0)init();
                    localStorage.setItem("PWnotes", JSON.stringify(pwNotes));
                    for (let i = 0; i < pwNotes.list.length; i++) {
                        localStorage.setItem(pwNotes.list[i].noteId, JSON.stringify(res_noteMap[pwNotes.list[i].noteId]));
                    }
                }else if (res_pwNotes.version < pwNotes.version) {
                    upload();
                }
            } else {
                if (pwNotes) upload();
            }
        },
        error:function () {
            $("#tips").remove();
            $("header").after("\n" +
                "<div class=\"aui-tips aui-margin-b-15\" id=\"tips\" hidden>\n" +
                "<i class=\"aui-iconfont aui-icon-info\"></i>\n" +
                "<div class=\"aui-tips-title\">云同步，请检查网络！</div>\n" +
                "<i class=\"aui-iconfont aui-icon-close\" tapmode=\"\" onclick=\"closeTips()\"></i>\n" +
                "</div>");
            return;
        }
    })
}

function upload() {
    let data = {
        pwNotes: pwNotes,
        noteMap: {}
    }
    for (let i = 0; i < pwNotes.list.length; i++) {
        data.noteMap[pwNotes.list[i].noteId] = JSON.parse(localStorage.getItem(pwNotes.list[i].noteId));
    }
    var upload_data = {
        data: encrypt(JSON.stringify(data), token).toString()
    }
    $.ajax({
        url: RE_url+"/upload_account/" + key,
        type: "post",
        data: upload_data,
        success: function (res) {
            console.log(res);
            if (res == "上传成功") return;
        },
        error:function () {
            $("#tips").remove();
            $("header").after("\n" +
                "<div class=\"aui-tips aui-margin-b-15\" id=\"tips\" hidden>\n" +
                "<i class=\"aui-iconfont aui-icon-info\"></i>\n" +
                "<div class=\"aui-tips-title\">云同步失败，请检查网络！</div>\n" +
                "<i class=\"aui-iconfont aui-icon-close\" tapmode=\"\" onclick=\"closeTips()\"></i>\n" +
                "</div>");
            return;
        }
    })
}
var iv = "ABCDEF1234123412";//十六位十六进制数作为密钥偏移量

function encrypt(text, key) {
    return CryptoJS.AES.encrypt(text, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(iv),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    })
}

function decrypt(text, key){
    var result = CryptoJS.AES.decrypt(text,CryptoJS.enc.Utf8.parse(key),{
        iv:CryptoJS.enc.Utf8.parse(iv),
        mode:CryptoJS.mode.CBC,
        padding:CryptoJS.pad.Pkcs7
    })
    return result.toString(CryptoJS.enc.Utf8)
}
function closeTips(){
    $api.remove($api.byId("tips"));
}